package com.distribute.framework.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.distribute.framework.core.web.helper.Utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.distribute.framework.core.lang.Protocol;

public class Api {

	public static Protocol execue(String url, String appid, String secret,String method,String token,Map<String,Object> params,Integer timeout){
		String timestamp = Utils.date(new Date(), "yyyy-MM-dd HH:mm:ss");
		StringBuffer response = new StringBuffer();
		PostMethod postMethod = new PostMethod(url); 		
		try{
			HttpClient client=new HttpClient();
			client.setConnectionTimeout(Utils.or(timeout,2000));
			client.setTimeout(Utils.or(timeout,2000));
			client.getHttpConnectionManager().getParams().setConnectionTimeout(Utils.or(timeout,2000));
			client.getHttpConnectionManager().getParams().setSoTimeout(Utils.or(timeout,2000));
			
			if(method==null){
				return Protocol.create(false, "method不能为空");
			}
			if(appid==null){
				return Protocol.create(false, "appid不能为空");
			}
			Map<String,String> postData = new HashMap();
			postData.put("method", method);
			postData.put("appid", appid);
			postData.put("token", Utils.or(token, ""));
			postData.put("timestamp", timestamp);
			postData.put("params", JSON.toJSONString(params));
			postData.put("sign", sign(secret, postData));
			
			Set<String> keyset = postData.keySet();			
			Part[] parts = new Part[keyset.size()];
			int i=0;
			for(String key:keyset){
				String value =(String) postData.get(key);
				parts[i++]=new StringPart(key, value,Utils.UTF8);
			}
			postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,Utils.UTF8);
			if(Utils.or(timeout,2000)<100){
				postMethod.setParameter("Connection", "close");
			}
			postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));		
			client.executeMethod(postMethod);
            if (postMethod.getStatusCode() == HttpStatus.SC_OK){  
                BufferedReader reader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(),Utils.UTF8));  
                String line=null;
                while ((line = reader.readLine()) != null){  
                     response.append(line);  
                }  
                reader.close();  
            } 
            
            JSONObject json = JSON.parseObject(response.toString());
            Protocol protocol = JSON.toJavaObject(json, Protocol.class);
            protocol.setData((Map) json.get("data"));     
            protocol.setList((List) json.get("list"));
            return protocol;
		}catch(java.net.SocketTimeoutException ste){
			return Protocol.create(false, "网络超时 - "+ste.getMessage());
		}catch(Exception ex){
			return Protocol.create(false, "系统繁忙 - "+ex.getMessage());
		}catch(Error er){
			return Protocol.create(false, "系统繁忙 - "+er.getMessage());
		}finally{
			postMethod.releaseConnection();
		}
	}

	/**
	 * 获取加密码串
	 * @param secret
	 * @param params
	 * @return
	 */
	public static String sign(String secret,Map<String,String> params){
		//按参数名asscic码排序
		List<String> names=new ArrayList();
		names.addAll(params.keySet());
		java.util.Collections.sort(names);
		String strSign = secret;
		for(String key:names)
			strSign+=key+params.get(key);
		strSign+=secret;
		return Utils.md5(strSign).toUpperCase();
	}
	

}